import React, { useState, useEffect } from 'react';
import './SettingPage.css';
import Breadcrumb from '../../components/Breadcrumb';
import BasicSettings from './BasicSettings';
import UserSettings from './UserSettings';
import PersonalizationSettings from './PersonalizationSettings';
import {
  SystemSettings,
  getDefaultSystemSettings,
  BasicSettings as BasicSettingsType,
  UserSettings as UserSettingsType,
  PersonalizationSettings as PersonalizationSettingsType,
  loadSettingsFromLocalStorage
} from './SettingsTypes';

// 定义设置页面的主组件
const SettingPage: React.FC = () => {
  // 状态管理
  const [activePage, setActivePage] = useState<'basic' | 'user' | 'personalization'>('basic');
  const [basicSettings, setBasicSettings] = useState<BasicSettingsType | null>(null);
  const [userSettings, setUserSettings] = useState<UserSettingsType | null>(null);
  const [personalizationSettings, setPersonalizationSettings] = useState<PersonalizationSettingsType | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 初始化主题
  useEffect(() => {
    // 尝试从本地存储获取主题设置
    try {
      const savedTheme = localStorage.getItem('theme') || 'system';
      applyTheme(savedTheme as 'light' | 'dark' | 'system');
    } catch (error) {
      console.error('初始化主题失败:', error);
    }
  }, []);

  // 应用主题
  const applyTheme = (theme: 'light' | 'dark' | 'system') => {
    if (theme === 'system') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      document.documentElement.classList.toggle('dark-theme', prefersDark);
      document.documentElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
    } else {
      document.documentElement.classList.toggle('dark-theme', theme === 'dark');
      document.documentElement.setAttribute('data-theme', theme);
    }
    localStorage.setItem('theme', theme);
  };

  // 加载所有设置
  useEffect(() => {
    const loadSettings = () => {
      try {
        // 获取默认设置
        const defaultSettings = getDefaultSystemSettings();
        
        // 加载基础设置
        const loadedBasicSettings = loadSettingsFromLocalStorage<BasicSettingsType>(
          'basicSettings', 
          defaultSettings.basic
        );
        setBasicSettings(loadedBasicSettings);

        // 加载用户设置
        const loadedUserSettings = loadSettingsFromLocalStorage<UserSettingsType>(
          'userSettings', 
          defaultSettings.user
        );
        setUserSettings(loadedUserSettings);

        // 加载个性化设置
        const loadedPersonalizationSettings = loadSettingsFromLocalStorage<PersonalizationSettingsType>(
          'personalizationSettings', 
          defaultSettings.personalization
        );
        setPersonalizationSettings(loadedPersonalizationSettings);
        
        // 应用主题设置
        if (loadedPersonalizationSettings) {
          applyTheme(loadedPersonalizationSettings.theme);
        }
      } catch (error) {
        console.error('加载设置失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadSettings();
  }, []);

  // 处理基础设置变化
  const handleBasicSettingsChange = (newSettings: BasicSettingsType) => {
    setBasicSettings(newSettings);
  };

  // 处理用户设置变化
  const handleUserSettingsChange = (newSettings: UserSettingsType) => {
    setUserSettings(newSettings);
  };

  // 处理个性化设置变化
  const handlePersonalizationSettingsChange = (newSettings: PersonalizationSettingsType) => {
    setPersonalizationSettings(newSettings);
    // 应用主题变化
    applyTheme(newSettings.theme);
  };

  // 渲染侧边导航菜单
  const renderSidebar = () => {
    const menuItems = [
      { id: 'basic' as const, label: '基础设置', icon: '⚙️' },
      { id: 'user' as const, label: '用户设置', icon: '👤' },
      { id: 'personalization' as const, label: '个性化设置', icon: '🎨' }
    ];

    return (
      <div className="settings-sidebar">
        <h3>设置菜单</h3>
        <ul className="settings-menu">
          {menuItems.map(item => (
            <li
              key={item.id}
              className={`menu-item ${activePage === item.id ? 'active' : ''}`}
              onClick={() => setActivePage(item.id)}
            >
              <span className="menu-icon">{item.icon}</span>
              <span className="menu-label">{item.label}</span>
            </li>
          ))}
        </ul>
      </div>
    );
  };

  // 渲染内容区域
  const renderContent = () => {
    if (isLoading || !basicSettings || !userSettings || !personalizationSettings) {
      return <div className="loading-container">加载设置中...</div>;
    }

    switch (activePage) {
      case 'basic':
        return (
          <BasicSettings
            initialSettings={basicSettings}
            onSettingsChange={handleBasicSettingsChange}
          />
        );
      case 'user':
        return (
          <UserSettings
            initialSettings={userSettings}
            onSettingsChange={handleUserSettingsChange}
          />
        );
      case 'personalization':
        return (
          <PersonalizationSettings
            initialSettings={personalizationSettings}
            onSettingsChange={handlePersonalizationSettingsChange}
          />
        );
      default:
        return <div>未知设置页面</div>;
    }
  };

  return (
    <div className="settings-page">
      <div className="page-header">
        <h1>系统设置</h1>
        <Breadcrumb
          items={[
            { id: 'dashboard', title: '首页' },
            { id: 'settings', title: '系统设置' }
          ]}
          activeItemId="settings"
        />
      </div>

      <div className="settings-container">
        {/* 侧边导航 */}
        {renderSidebar()}

        {/* 主内容区域 */}
        <div className="settings-content">
          <div className="content-header">
            <h2>
              {activePage === 'basic' && '基础设置'}
              {activePage === 'user' && '用户设置'}
              {activePage === 'personalization' && '个性化设置'}
            </h2>
          </div>
          <div className="content-body">
            {renderContent()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default SettingPage;